//
//  UITextView-Extension.swift
//  表情键盘
//
//  Created by 陈恒均 on 2018/2/24.
//  Copyright © 2018年 陈恒均. All rights reserved.
//

import UIKit

extension UITextView
{
    func getEmoticonString() -> String {
        let attrMStr = NSMutableAttributedString(attributedString: attributedText)
        let rang = NSRange(location: 0, length: attrMStr.length)
        
        attrMStr.enumerateAttributes(in: rang, options: []) { (dict, rang, _) in
            if let attachment = dict[NSAttributedStringKey.attachment] as? EmoticonAttachment{
                attrMStr.replaceCharacters(in: rang, with: attachment.chs!)
            }
        }
        return attrMStr.string
    }
    
    // MARK:- 根据图片创建属性字符串
    func insertEmoticon(emoticon : Emoticon) {
        if emoticon.isEmpty {
            return
        }
        if emoticon.isRemove {
            deleteBackward()
            return
        }
        if emoticon.emojiCode != nil {
            let textRang = selectedTextRange
            replace(textRang!, withText: emoticon.emojiCode!)
            return
        }
        let attachment = EmoticonAttachment()
        attachment.chs = emoticon.chs
        attachment.image = UIImage(contentsOfFile: emoticon.pngPath!)
        let font = self.font
        attachment.bounds = CGRect(x: 0, y: -4, width: (font?.lineHeight)!, height: (font?.lineHeight)!)
        
        let attrImagStr = NSAttributedString(attachment: attachment)
        let attrMStr  = NSMutableAttributedString(attributedString: attributedText)
        
        let rang = selectedRange
        attrMStr.replaceCharacters(in: rang, with: attrImagStr)
        
        attributedText = attrMStr
        
        self.font = font
        
        selectedRange = NSRange(location: rang.location + 1, length: 0)
        
    }
    
    
}
